package com.zhixianggou.caibaobox.user.shiro.utils;

import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.ExcessiveAttemptsException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authc.credential.HashedCredentialsMatcher;
import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;

import java.util.concurrent.atomic.AtomicInteger;
 




/**
 * @author xiaofengzhang
 * @version 1.0
 */
public class CustomCredentialsMatcher extends HashedCredentialsMatcher {
	
	private Cache<String, AtomicInteger> passwordRetryCache;

    public CustomCredentialsMatcher(CacheManager cacheManager) {
        passwordRetryCache = cacheManager.getCache("passwordRetryCache");
    }


    public boolean doCredentialsMatch(AuthenticationToken token, AuthenticationInfo info) {

    	UsernamePasswordToken authToken = (UsernamePasswordToken)token;

		String username = (String)authToken.getUsername();

		//retry count + 1
        AtomicInteger retryCount = passwordRetryCache.get(username);
        if(retryCount == null) {
            retryCount = new AtomicInteger(0);
            passwordRetryCache.put(username, retryCount);
        }

        if(retryCount.incrementAndGet() > 5) {
            //if retry count > 5 throw
            throw new ExcessiveAttemptsException();
        }

//		Object tokenCredentials = encrypt(String.valueOf(token.getPassword()));
		Object tokenCredentials = EndecryptUtils.encrypt(String.valueOf(authToken.getPassword()));
		Object accountCredentials = info.getCredentials();

		checkPwd(tokenCredentials,accountCredentials);

		// 将密码加密与系统加密后的密码校验，内容一致就返回true,不一致就返回false
		boolean matches = equals(tokenCredentials, accountCredentials);
		if(matches) {
            //clear retry count 清除缓存
            passwordRetryCache.remove(username);
        }
		return matches;
	}


	private void checkPwd(Object tokenCredentials, Object accountCredentials) {
		// TODO Auto-generated method stub
		byte[] accountBytes = toBytes(accountCredentials);
		char[] chars = toChars(accountBytes);
		StringBuffer sb = new StringBuffer();
		for (char b : chars) {
			sb.append(b);
		}
		System.out.println("传进的密码:"+tokenCredentials.toString());
		System.out.println("数据库的密码"+sb.toString());
	}

}
